"""
Verify image cache and download functionality
Test downloading and caching template cover images
"""
import os
import sys
import hashlib
from pathlib import Path
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Add project root to path
sys.path.insert(0, str(Path(__file__).parent.parent))

# Verify configuration
if not os.getenv("AIPPT_TOKEN"):
    print("ERROR: AIPPT_TOKEN not found in environment variables")
    print("Please set AIPPT_TOKEN in .env file")
    sys.exit(1)

from src.llm.aippt_app.services.template_service import TemplateService


def test_image_download_and_cache():
    """Test image download with caching"""
    print("=" * 60)
    print("Testing Image Cache and Download Functionality")
    print("=" * 60)

    # Initialize service
    service = TemplateService()

    # Test 1: Get templates to get cover URLs
    print("\n[Test 1] Getting template list to obtain cover URLs...")
    result = service.list_templates(current=1, size=3, template_type=1)

    if result.get('code') != 0:
        print(f"Failed to get templates: {result}")
        return False

    templates = result.get('data', [])
    if not templates:
        print("No templates found")
        return False

    print(f"Found {len(templates)} templates")

    # Test 2: Download and cache first template's cover image
    template = templates[0]
    cover_url = template.get('coverUrl')
    template_id = template.get('id')

    print(f"\n[Test 2] Testing image cache for template {template_id}")
    print(f"Cover URL: {cover_url}")

    # Clear cache for testing (if exists)
    cache_dir = Path(__file__).parent.parent / "cache" / "template_covers"

    # Clear all cache files for fresh test
    if cache_dir.exists():
        for cache_file in cache_dir.glob("*"):
            cache_file.unlink()
        print("Cleared existing cache files")

    # First download - should download from remote
    print("\n[First Request] Downloading from remote...")
    from src.llm.aippt_app.services.image_cache_service import ImageCacheService
    cache_service = ImageCacheService()

    local_path1 = cache_service.get_cached_image(cover_url)
    print(f"Local path: {local_path1}")
    print(f"File exists: {os.path.exists(local_path1)}")
    print(f"File size: {os.path.getsize(local_path1)} bytes")

    # Second download - should use cache
    print("\n[Second Request] Should use cached version...")
    local_path2 = cache_service.get_cached_image(cover_url)
    print(f"Local path: {local_path2}")
    print(f"Same path: {local_path1 == local_path2}")

    # Verify file integrity
    if os.path.exists(local_path1):
        with open(local_path1, 'rb') as f:
            content = f.read()
            file_hash = hashlib.md5(content).hexdigest()
            print(f"\nFile hash: {file_hash}")
            print(f"File is valid image: {content[:8] == b'\\x89PNG\\r\\n\\x1a\\n'}")

    # Test 3: Test with multiple images
    print("\n[Test 3] Testing cache with multiple images...")
    for i, template in enumerate(templates[:3], 1):
        tid = template.get('id')
        curl = template.get('coverUrl')
        print(f"\nTemplate {i}: {tid}")
        local_path = cache_service.get_cached_image(curl)
        print(f"  Cached at: {local_path}")
        print(f"  Exists: {os.path.exists(local_path)}")

    # List cache directory
    print(f"\n[Cache Directory] {cache_dir}")
    if cache_dir.exists():
        cached_files = list(cache_dir.glob("*"))
        print(f"Total cached files: {len(cached_files)}")
        for f in cached_files:
            size_kb = f.stat().st_size / 1024
            print(f"  - {f.name} ({size_kb:.1f} KB)")

    print("\n" + "=" * 60)
    print("Image Cache Test PASSED")
    print("=" * 60)
    return True


if __name__ == "__main__":
    try:
        success = test_image_download_and_cache()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"\nTest failed with error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
